<?php
// This plugin is only for Nette framework 

/*
CREATE TABLE `plugin_doc_link` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL,
  `url` varchar(255) NOT NULL,
  `shortName` varchar(100) NOT NULL,
  PRIMARY KEY  (`id`)
)
 */

class DocumentationPlugin extends Plugin
{
    public function startup()
    {
        $this->onMessage = array($this, 'onMessage');
    }

    public function onMessage(Message $data)
    {
        $links = array();
    
        if((substr($data->getBody(), 0, 4) == '!doc') AND (strlen($data->getBody()) > 4)){
            $doc = substr($data->getBody(), 5);
            list($command) = explode(" ", $doc);
            switch ($command) {
                case 'add':
                    
                    break;
                default:
                    $fetch = $this->getDocFromShortName($command);
                    if(! is_null($fetch) ){
                        $links[ $fetch['name'] ] = $fetch['url'];
                    }
            }
        }else{
            preg_match_all('#nette\\\([^ ]+)#i', $data->getBody(), $match);

            if(count($match[0]) == 0)
                return;
            
            foreach($match[0] as $namespace){
                if($namespace[0] != '\\')
                    $namespace = '\\'.$namespace;
                    
                $url = $this->getDoc($namespace);
                
                if(!is_null($url)){
                    $links[$namespace] = $url; 
                }
            }
        }
 
        if(count($links) > 0 )
        {
            $message = "Documentation Helper:";
            foreach($links as $namespace => $link){
                $message .= "\n".$namespace." ".$link;
            }
            $this->sendMessage($message, $message->getFrom());
        }
    }

    public function getDocFromShortName($name)
    {
        $name = strtolower($name);
        $fetch = dibi::select('*')->from('plugin_doc_link')->where('shortName=%s',$name)->fetch();
        return $fetch;
    }

    public function getDoc($name)
    {
        $name = strtolower($name);
        $fetch = dibi::select('*')->from('plugin_doc_link')->where('name=%s',$name)->fetch();
        return $fetch?$fetch['url']:NULL;
    }
}

?>